package com.easystudy.util;

import java.net.URI;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @文件名称: TokenUtil.java
 * @功能描述: Token处理工具
 * @版权信息：  www.easystudy.com
 * @技术交流：  961179337(QQ群)
 * @编写作者：  lixx2048@163.com
 * @联系方式：  941415509(QQ)
 * @开发日期：  2020年8月17日
 * @历史版本： V1.0 
 * @备注信息：
 */
@Component
public class TokenUtil {

    @Resource(name = "tokenTemplate")
    private RestTemplate tokenTemplate;

    public String getBearerTokenByClientCredentials(String clientId, String clientSecret, String tokenEndpoint){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBasicAuth(clientId, clientSecret);
        
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "client_credentials");
        
        RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(params, httpHeaders, HttpMethod.POST, URI.create(tokenEndpoint));
        ResponseEntity<TokenDTO> exchange = tokenTemplate.exchange(requestEntity, TokenDTO.class);
        if (exchange.getStatusCode().is2xxSuccessful()) {
            return "Bearer " + Objects.requireNonNull(exchange.getBody()).getAccessToken();
        }else{
            return "";
        }
    }

    @Data
    @JsonInclude(Include.NON_NULL)
    @AllArgsConstructor
    @NoArgsConstructor
    static class TokenDTO {
        @JsonProperty("access_token")
        private String accessToken;
        @JsonProperty("refresh_token")
        private String refreshToken;
        @JsonProperty("token_type")
        private String tokenType;
        @JsonProperty("expires_in")
        private String expiresIn;
        @JsonProperty("scope")
        private String scope;
    }

    @Bean("tokenTemplate")
    public RestTemplate tokenTemplate(){
        return new RestTemplate();
    }
}